package com.bjpowernode.aop;

import com.bjpowernode.annotation.DataScope;
import com.bjpowernode.entity.TRole;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.query.BaseQuery;
import com.bjpowernode.util.LoginInfoUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 数据权限切面类
 */
@Component
@Aspect //切面类
public class DataScopeAspect {

    //在自定义注解的方法上添加切面
    @Around("@annotation(com.bjpowernode.annotation.DataScope)")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取方法的签名对象
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        //获取方法的DataScope注解对象
        DataScope dataScope = methodSignature.getMethod().getAnnotation(DataScope.class);

        //获取注解中的属性
        String tableAlias = dataScope.tableAlias();
        String columnName = dataScope.columnName();

        //获取当前的登录用户信息
        TUser tUser = LoginInfoUtil.getCurrentLoginUser();

        //获取用户角色
        List<TRole> tRoleList = tUser.getTRoleList();

        //判断角色中是否包含管理员
        boolean isAdmin = tRoleList.stream().anyMatch(tRole -> tRole.getRole().contains("admin"));

        if (!isAdmin) {
            //当前用户不是管理员
            //获取方法的第一个参数
            Object params = joinPoint.getArgs()[0];

            if (params instanceof BaseQuery) {
                BaseQuery baseQuery = (BaseQuery)params;

                //tu.id = 3
                baseQuery.setFilterSQL(tableAlias + "." + columnName + " = " + tUser.getId());
            }

        }

        Object proceed = joinPoint.proceed();

        return proceed;
    }
}
